package czk.concrent.enjoyModelWithNotLock.atomicRefence;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * ABA问题
 * 其余线程将A->B->A compareAndSet的CAS交换依然会成功
 * @Author:ChenZhangKun
 * @Date: 2020/6/14 20:56
 */
public class Test1 {
    public static void main(String[] args) {
        //
        AtomicReference<String> atomicReference=new AtomicReference<>("A");
        // 获取原来的值
        String s = atomicReference.get();
        // 新线程来改变
        new Thread(()->{
            atomicReference.updateAndGet(i->"B");
            System.out.println("值变成了 "+atomicReference.get());
            atomicReference.updateAndGet(i->"A");
            System.out.println("值变成了 "+atomicReference.get());
        }).start();
        try {
            Thread.sleep(2*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // cas比较
        boolean b = atomicReference.compareAndSet(s, "B");
        // true
        System.out.println(b==true?"成功":"失败");
    }
}
